package it.nard.controller;

import it.nard.constant.Constant;
import it.nard.listener.ControlDocumentListener;
import it.nard.persistence.dao.LatteinentrataMapper;
import it.nard.persistence.model.Allevatori;
import it.nard.persistence.model.Latteinentrata;
import it.nard.persistence.model.LatteinentrataExample;
import it.nard.persistence.model.Latteingiacenza;
import it.nard.persistence.model.Latteinuscita;
import it.nard.persistence.model.Rmozzarella;
import it.nard.persistence.model.RmozzarellaExample;
import it.nard.persistence.model.Rprovola;
import it.nard.persistence.model.Rricotta;
import it.nard.sourceframes.AllevatoriPnl;
import it.nard.sourceframes.GenerateReportPnl;
import it.nard.sourceframes.LatteInEntrataPnl;
import it.nard.sourceframes.LatteInGiacenzaPnl;
import it.nard.sourceframes.MainFrame;
import it.nard.sourceframes.RMozzarellaPnl;
import it.nard.utils.TimeSlots;

import java.awt.Color;
import java.awt.Desktop;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

import org.apache.ibatis.session.SqlSession;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
import org.jdesktop.swingx.decorator.HighlighterFactory;
import org.joda.time.DateTime;

public class GeneraReportController  extends BasicController{


	
	
	public GeneraReportController(){
		super("Genera Reports", null);
		
	}

	
	public void select (MouseEvent mevent) {
		
		GenerateReportPnl reports = ((GenerateReportPnl)controlPnl);
		JTextArea textAreaMsg = reports.getJTextArea0();
		String rootFile = reports.getJTextField0().getText();
		mainFrame.sendMessage("Generazione automatica di Reports.", MainFrame.OK_MESSAGE);
		
		boolean mozzarellaToGenerate = reports.getJCheckBox0().isSelected();
		boolean provolaToGenerate = reports.getJCheckBox1().isSelected();
		boolean ricottaToGenerate = reports.getJCheckBox2().isSelected();
		
		boolean latteInEntrataToGenerate = reports.getJCheckBox3().isSelected();
		boolean latteInGiacenzaToGenerate = reports.getJCheckBox4().isSelected();
		boolean latteInUscitaToGenerate = reports.getJCheckBox5().isSelected();
		
		Date dt1 = reports.getJXDatePicker0().getDate();
		Date dt2 = reports.getJXDatePicker1().getDate();
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		if(mozzarellaToGenerate){
			textAreaMsg.setText(textAreaMsg.getText()+"\n"+" Recuperando Reports Mozzarella Periodo: "+sdf.format(dt1)+" - "+sdf.format(dt2) );
			textAreaMsg.revalidate();
				List<Rmozzarella> mozzarellaList = MainController.getRMozzarellaController().retriveListFromDates(dt1, dt2);
				Iterator<Rmozzarella> iter = mozzarellaList.iterator();
				while(iter.hasNext()){
					Rmozzarella elem = iter.next();
					textAreaMsg.setText(textAreaMsg.getText()+"\n"+" Report Mozzarella del: "+elem.getDataProduzione() );
					List<Rmozzarella> list = new ArrayList<Rmozzarella>();
					list.add(elem);
					String path = makeDirFromDate(rootFile+"/", elem.getDataproduzione());
					path = path.concat("/"+MainController.getRMozzarellaController().getControllerCode()+"_"+elem.getDataproduzione());
					print(list, MainController.getRMozzarellaController().getControllerCode(),path);
					textAreaMsg.setText(textAreaMsg.getText()+"... generato correttamente." );
					textAreaMsg.revalidate();
				}
		
		}
		
		if(provolaToGenerate){
			textAreaMsg.setText(textAreaMsg.getText()+"\n"+" Recuperando Reports Provola Periodo: "+sdf.format(dt1)+" - "+sdf.format(dt2) );
			textAreaMsg.revalidate();
				List<Rprovola> mozzarellaList = MainController.getRProvolaController().retriveListFromDates(dt1, dt2);
				Iterator<Rprovola> iter = mozzarellaList.iterator();
				while(iter.hasNext()){
					Rprovola elem = iter.next();
					textAreaMsg.setText(textAreaMsg.getText()+"\n"+" Report Provola del: "+elem.getDataProduzione() );
					List<Rprovola> list = new ArrayList<Rprovola>();
					list.add(elem);
					String path = makeDirFromDate(rootFile+"/", elem.getDataproduzione());
					path = path.concat("/"+MainController.getRProvolaController().getControllerCode()+"_"+elem.getDataproduzione());
					print(list, MainController.getRProvolaController().getControllerCode(),path);
					textAreaMsg.setText(textAreaMsg.getText()+"... generato correttamente." );
					textAreaMsg.revalidate();
				}
		
		}
		
		if(ricottaToGenerate){
			textAreaMsg.setText(textAreaMsg.getText()+"\n"+" Recuperando Reports Ricotta Periodo: "+sdf.format(dt1)+" - "+sdf.format(dt2) );
			textAreaMsg.revalidate();
				List<Rricotta> mozzarellaList = MainController.getRRicottaController().retriveListFromDates(dt1, dt2);
				Iterator<Rricotta> iter = mozzarellaList.iterator();
				while(iter.hasNext()){
					Rricotta elem = iter.next();
					textAreaMsg.setText(textAreaMsg.getText()+"\n"+" Report Ricotta del: "+elem.getDataProduzione() );
					List<Rricotta> list = new ArrayList<Rricotta>();
					list.add(elem);
					String path = makeDirFromDate(rootFile+"/", elem.getDataproduzione());
					path = path.concat("/"+MainController.getRRicottaController().getControllerCode()+"_"+elem.getDataproduzione());
					print(list, MainController.getRRicottaController().getControllerCode(),path);
					textAreaMsg.setText(textAreaMsg.getText()+"... generato correttamente." );
					textAreaMsg.revalidate();
				}
		
		}
		
		
		if(latteInEntrataToGenerate){
			textAreaMsg.setText(textAreaMsg.getText()+"\n"+" Recuperando Reports Latte in Entrata Periodo: "+sdf.format(dt1)+" - "+sdf.format(dt2) );
			textAreaMsg.revalidate();
				List<Latteinentrata> mozzarellaList = MainController.getLatteInEntrataController().retriveListFromDates(dt1, dt2);
				HashMap<Integer, ArrayList<Latteinentrata>> listHash = createSlotsInEntrata(mozzarellaList);
				
				Iterator<Integer> iter = listHash.keySet().iterator();
				while(iter.hasNext()){
					Integer elem = iter.next();
					try {
						textAreaMsg.setText(textAreaMsg.getText()+"\n"+" Report Latte In Entrata del: "+sdf.format(SDF_4_DB.parse(elem.toString())) );
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					List<Latteinentrata> list = listHash.get(elem);
					
					String path = makeDirFromDate(rootFile+"/", elem);
					path = path.concat("/"+MainController.getLatteInEntrataController().getControllerCode()+"_"+elem);
					print(list, MainController.getLatteInEntrataController().getControllerCode(),path);
					textAreaMsg.setText(textAreaMsg.getText()+"... generato correttamente." );
					textAreaMsg.revalidate();
				}
		
		}
		if(latteInGiacenzaToGenerate){
			textAreaMsg.setText(textAreaMsg.getText()+"\n"+" Recuperando Reports Latte in Giacenza Periodo: "+sdf.format(dt1)+" - "+sdf.format(dt2) );
			textAreaMsg.revalidate();
				List<Latteingiacenza> mozzarellaList = MainController.getLatteInGiacenzaController().retriveListFromDates(dt1, dt2);
				HashMap<Integer, ArrayList<Latteingiacenza>> listHash = createSlotsInGiacenza(mozzarellaList);
				
				Iterator<Integer> iter = listHash.keySet().iterator();
				while(iter.hasNext()){
					Integer elem = iter.next();
					try {
						textAreaMsg.setText(textAreaMsg.getText()+"\n"+" Report Latte In Giacenza del: "+sdf.format(SDF_4_DB.parse(elem.toString())) );
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					List<Latteingiacenza> list = listHash.get(elem);
					
					String path = makeDirFromDate(rootFile+"/", elem);
					path = path.concat("/"+MainController.getLatteInGiacenzaController().getControllerCode()+"_"+elem);
					print(list, MainController.getLatteInGiacenzaController().getControllerCode(),path);
					textAreaMsg.setText(textAreaMsg.getText()+"... generato correttamente." );
					textAreaMsg.revalidate();
				}
		
		}
		
		if(latteInUscitaToGenerate){
			textAreaMsg.setText(textAreaMsg.getText()+"\n"+" Recuperando Reports Latte in Uscita Periodo: "+sdf.format(dt1)+" - "+sdf.format(dt2) );
			textAreaMsg.revalidate();
				List<Latteinuscita> mozzarellaList = MainController.getLatteInUscitaController().retriveListFromDates(dt1, dt2);
				HashMap<Integer, ArrayList<Latteinuscita>> listHash = createSlotsInUscita(mozzarellaList);
				
				Iterator<Integer> iter = listHash.keySet().iterator();
				while(iter.hasNext()){
					Integer elem = iter.next();
					try {
						textAreaMsg.setText(textAreaMsg.getText()+"\n"+" Report Latte In Uscita del: "+sdf.format(SDF_4_DB.parse(elem.toString())) );
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					List<Latteinuscita> list = listHash.get(elem);
					
					String path = makeDirFromDate(rootFile+"/", elem);
					path = path.concat("/"+MainController.getLatteInUscitaController().getControllerCode()+"_"+elem);
					print(list, MainController.getLatteInUscitaController().getControllerCode(),path);
					textAreaMsg.setText(textAreaMsg.getText()+"... generato correttamente." );
					textAreaMsg.revalidate();
				}
		
		}
		
	}


	private HashMap<Integer, ArrayList<Latteinentrata>> createSlotsInEntrata (List<Latteinentrata> in){
		HashMap<Integer, ArrayList<Latteinentrata>> out = new HashMap<Integer,ArrayList<Latteinentrata>>();
		
		Iterator<Latteinentrata> iter = in.iterator();
		while(iter.hasNext()){
			Latteinentrata elem = iter.next();
			if(out.get(elem.getDatain())==null)
				out.put(elem.getDatain(),new ArrayList<Latteinentrata>());
				
				out.get(elem.getDatain()).add(elem);
				
			
		}
		return out;
	}
	
	
	private HashMap<Integer, ArrayList<Latteinuscita>> createSlotsInUscita (List<Latteinuscita> in){
		HashMap<Integer, ArrayList<Latteinuscita>> out = new HashMap<Integer,ArrayList<Latteinuscita>>();
		
		Iterator<Latteinuscita> iter = in.iterator();
		while(iter.hasNext()){
			Latteinuscita elem = iter.next();
			if(out.get(elem.getDatain())==null)
				out.put(elem.getDatain(),new ArrayList<Latteinuscita>());
				
				out.get(elem.getDatain()).add(elem);
				
			
		}
		return out;
	}
	
	private HashMap<Integer, ArrayList<Latteingiacenza>> createSlotsInGiacenza (List<Latteingiacenza> in){
		HashMap<Integer, ArrayList<Latteingiacenza>> out = new HashMap<Integer,ArrayList<Latteingiacenza>>();
		
		Iterator<Latteingiacenza> iter = in.iterator();
		while(iter.hasNext()){
			Latteingiacenza elem = iter.next();
			if(out.get(elem.getDatain())==null)
				out.put(elem.getDatain(),new ArrayList<Latteingiacenza>());
				
				out.get(elem.getDatain()).add(elem);
				
			
		}
		return out;
	}
	
	public String makeDirFromDate (String baseDir, Integer date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String out = "";
		try {
			out= baseDir+sdf.format(SDF_4_DB.parse(String.valueOf(date)));
			File dir  = new File(out);
			dir.mkdirs();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return out;
	}
	
	public void print (List< ?extends Object> list, String controllerCode, String pathFile){
		
		
		
		String tempFile = pathFile;
		tempFile = tempFile.concat(".pdf");
		
		jasperReportManager.generateReport(list,controllerCode,tempFile , true);
	}
	
	
	
	
	
	
	public void delete (){
		
	
	}
	
	public void insert (){
		
	}
	
	public   GenerateReportPnl getMainPanel(){
		 controlPnl = new GenerateReportPnl(this);
			
		 return (GenerateReportPnl) controlPnl;
	}

	

	@Override
	public String getControllerCode() {
		return "";
	}

	@Override
	public void clearPnl() {
		
	}


	@Override
	public void onDateSelect() {
		
	}
	
	
	
	
	
	
	
}
